<?php

namespace app\admin\controller;

use app\admin\model\User;
use think\App;
use think\Exception;

/**
 * @title 基础的类库
 * Class BaseController
 * @package app\admin\controller
 */
class BaseController extends \app\BaseController
{
    const JSON_SUCCESS_STATUS = 1;  // 成功的代码
    const JSON_ERROR_STATUS = 0;    // 失败的代码

    private $wxapp_id;
    protected $app;

    /**
     * BaseController constructor.
     * @param App $app
     * @throws Exception
     */
    public function __construct(App $app)
    {
        parent::initialize();
        $this->app = $app;
        $this->wxapp_id = $this->getWxappId();

    }

    /**
     * @title 获取wxapp_id
     * @throws Exception
     */
    public function getWxappId()
    {

        if (!$wxapp_id = $this->app->request->param("wxapp_id")) {
            throw new Exception(["msg" => "确实必要参数：wxap_id"]);
        }
    }

    /**
     * @title 获取用户
     * @param bool $is_force
     */
    protected function getUSer($is_force = true)
    {
        if (!$token = $this->request->param("token")) {
            $is_force && $this->throwError("缺少必要参数:token");
        }

    }

    /**
     * 输出错误信息
     * @param int $code
     * @param $msg
     * @throws Exception
     */
    protected function throwError($msg, $code = 0)
    {
        throw new Exception(['code' => $code, 'msg' => $msg]);
    }

    /**
     * @title json
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return array
     */
    protected function renderJson($code = self::JSON_SUCCESS_STATUS, $msg = "", $data = [])
    {
        return compact("code", "msg", "data");
    }

    /**
     * @title 成功
     * @param array $data
     * @param string $msg
     * @return array
     */
    public function renderSuccess($data = [], $msg = "")
    {
        return $this->renderJson(self::JSON_SUCCESS_STATUS, $msg, $data);
    }

    /**
     * @title 失败
     * @param array $data
     * @param string $msg
     * @return array
     */
    public function renderError($data = [], $msg = "")
    {
        return $this->renderJson(self::JSON_ERROR_STATUS, $msg, $data);
    }

}